import dayjs from 'dayjs'
import * as echarts from 'echarts/core'
import { ElMessage } from 'element-plus'
import { getSystemExport } from '@renderer/ajax//api/common'
const { ipcRenderer } = require("electron");
const fs = require('fs')

// 获取 ID 数组
export const getIdList = (key: string, list: any) => {
    let arr: number[] = []
    list.forEach((item: any) => arr.push(item[key]))
    return arr
}
/**
 * 日期格式化
 * @param {*} date 日期对象
 * @param {*} fmt 时间格式 默认为 YYYY-MM-DD HH:mm:ss
 */
export const dateFormat = (date: any, fmt: string = 'YYYY-MM-DD HH:mm:ss') => dayjs(date).format(fmt)
/**
 * 获取开始/结束时间
 * @param {*}  type dayStartOf dayEndOf weekStartOf weekEndOf monthStartOf monthEndOf yearStartOf yearEndOf
 * * @param {*} fmt 时间格式 默认为 YYYY-MM-DD HH:mm:ss
 */
export const getDate = (type: string, fmt: string = 'YYYY-MM-DD HH:mm:ss') => {
    let date = {
        dayStartOf: dayjs(dayjs().date(dayjs().date()).startOf('day').$d).format(fmt),
        dayEndOf: dayjs(dayjs().date(dayjs().date()).endOf('day').$d).format(fmt),
        weekStartOf: dayjs(dayjs().day(dayjs().day()).startOf('week').add(1, 'day').$d).format(fmt),
        weekEndOf: dayjs(dayjs().day(dayjs().day()).endOf('week').add(1, 'day').$d).format(fmt),
        monthStartOf: dayjs(dayjs().month(dayjs().month()).startOf('month').$d).format(fmt),
        monthEndOf: dayjs(dayjs().month(dayjs().month()).endOf('month').$d).format(fmt),
        yearStartOf: dayjs(dayjs().year(dayjs().year()).startOf('year').$d).format(fmt),
        yearEndOf: dayjs(dayjs().year(dayjs().year()).endOf('year').$d).format(fmt)
    }
    return date[type]
}
//导出echarts图片
export const export2Img = async (val: any, fileName: string) => {
    let Echarts = echarts.init(val)
    let file = Echarts.getConnectedDataURL({
        type: 'png',
        pixelRatio: 1.5,
        backgroundColor: '#fff'
    })
    let Content = file.replace(/^data:image\/\w+;base64,/, '')
    let FileName = fileName + '.png'
    // 把base64码转成buffer对象
    let buf = new Buffer(Content, 'base64')
    let params = {
        title: '请选择下载文件的目录',
        buttonLabel: '保存',
        pathName: FileName,
    }
    ipcRenderer.invoke("open-savebox", params).then((res) => {
        console.log(res, '1')
        fs.writeFileSync(res.filePath, buf)
        ElMessage.success('下载成功')
    });
    // await getSystemExport({ Type: 1, Content, FileName, Extname: "png", })
    // ElMessage.success('下载成功')
}

export const toBuffer = (ab) => {
    var buf = new Buffer(ab.byteLength);
    var view = new Uint8Array(ab);
    for (var i = 0; i < buf.length; ++i) {
        buf[i] = view[i];
    }
    return buf;
}

export const getVideoImage = (url: string, w?: number, h?: number) => {
    return `${url}?x-oss-process=video/snapshot,t_0,f_jpg,w_${w},h_${h},m_fast`
}

// 上传文件类型
import pdfImg from '@renderer/assets/imgs/file/pdf.png'
import docImg from '@renderer/assets/imgs/file/doc.png'
import xlsImg from '@renderer/assets/imgs/file/xls.png'
import pptImg from '@renderer/assets/imgs/file/ppt.png'
import picImg from '@renderer/assets/imgs/file/pic.png'
import textImg from '@renderer/assets/imgs/file/text.png'
import fileImg from '@renderer/assets/imgs/file/file.png'

const fileTYpe = {
    '.pdf': pdfImg,
    '.doc': docImg,
    '.docx': docImg,
    '.xls': xlsImg,
    '.xlsx': xlsImg,
    '.ppt': pptImg,
    '.pptx': pptImg,
    '.png': picImg,
    '.jpg': picImg,
    '.jpeg': picImg,
    '.text': textImg,
    '.txt': textImg
}
// 获取对应得图标
export const getSuffixIcon = (str: string) => {
    if (str) {
        let suffix = str.substring(str.lastIndexOf('.'))
        let types = Object.keys(fileTYpe)
        if (types.includes(suffix)) {
            return fileTYpe[suffix]
        } else {
            return fileImg
        }
    } else {
        return fileImg
    }
}


/**
 * 深拷贝
 * @param value 
 * @returns 
 */
export const cloneDeep = (value, clonedMap = new WeakMap()) => {
    if (!isObject(value)) {
        return value;
    }

    // 处理循环引用
    if (clonedMap.has(value)) {
        return clonedMap.get(value);
    }

    // 创建克隆对象
    let cloneValue;
    if (Array.isArray(value)) {
        cloneValue = [];
    } else if (value instanceof Date) {
        cloneValue = new Date(value);
    } else if (value instanceof RegExp) {
        cloneValue = new RegExp(value.source, getRegExpFlags(value));
    } else if (value instanceof Map) {
        cloneValue = new Map();
        value.forEach((innerValue, key) => {
            cloneValue.set(key, cloneDeep(innerValue, clonedMap));
        });
    } else if (value instanceof Set) {
        cloneValue = new Set();
        value.forEach((innerValue) => {
            cloneValue.add(cloneDeep(innerValue, clonedMap));
        });
    } else {
        cloneValue = {};
    }

    // 记录循环引用
    clonedMap.set(value, cloneValue);

    // 深拷贝属性
    for (let key in value) {
        cloneValue[key] = cloneDeep(value[key], clonedMap);
    }

    return cloneValue;
}

// 判断是否为对象
export const isObject = (value) => {
    const type = typeof value;
    return value != null && (type == 'object' || type == 'function');
}

const getRegExpFlags = (regexp) => {
    let flags = '';
    if (regexp.global) flags += 'g';
    if (regexp.ignoreCase) flags += 'i';
    if (regexp.multiline) flags += 'm';
    if (regexp.sticky) flags += 'y';
    if (regexp.unicode) flags += 'u';
    return flags;
}